<?php

use Phalcon\Mvc\Model\Validator\Uniqueness as Uniqueness;


class GroupRequests extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var integer
     */
    public $group_id;

    /**
     *
     * @var integer
     */
    public $user_id;

    /**
     *
     * @var string
     */
    public $date_created;

    /**
     * Independent Column Mapping.
     */
    public function columnMap()
    {
        return array(
            'id' => 'id', 
            'group_id' => 'group_id', 
            'user_id' => 'user_id', 
            'date_created' => 'date_created'
        );
    }

    public function beforeValidationOnCreate()
    {
        $this->validate(new Uniqueness(
          array(
                "field"   => "user_id",
                "message" => "You already sent a request"
            )
        ));

        $this->date_created = CURR_DATE;
        

        if ($this->validationHasFailed() == true)
        {
            return false;
        }
    }

    public function checkIfExists($user_id,$group_id)
    {   
        return GroupRequests::findFirst(array(
                    'conditions'=>'user_id = ?0 and group_id = ?1',
                    'bind'=>array(0=>$user_id,1=>$group_id)
                ));
    }

    public function listRequests($group_id)
    {
        $phql = "SELECT gr.id,gr.user_id,uat.fname,uat.lname,uat.profile_pic,uat.work_experience FROM GroupRequests gr 
                 LEFT JOIN UserAccountTb uat ON gr.user_id = uat.id
                 WHERE gr.group_id = ?0";
        $data = $this->modelsManager->executeQuery($phql,array(0=>$group_id));
        return @$data;
    }
}
